package com.dream.xiaobo.service.impl;

import com.dream.xiaobo.dao.impl.CartDaoImpl;
import com.dream.xiaobo.dao.impl.ProductDaoImpl;
import com.dream.xiaobo.entity.Cart;
import com.dream.xiaobo.entity.Product;
import com.dream.xiaobo.service.CartService;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author xiaobo
 * @date 2021/9/1 - 9:40
 */
public class CartServiceImpl implements CartService {

    //创建carDao实例化对象
    private CartDaoImpl cartDao = new CartDaoImpl();
    //创建productDao实例化对象
    private ProductDaoImpl productDao = new ProductDaoImpl();

    /**
     * 添加到购物车逻辑
     * @param uId
     * @param pId
     * @throws IllegalAccessException
     * @throws SQLException
     * @throws InvocationTargetException
     */
    @Override
    public void createCart(Integer uId, String pId) throws IllegalAccessException, SQLException, InvocationTargetException {

        //调用根据用户Id和商品Id查询的方法
        Cart cart = cartDao.hasCart(uId, pId);
        //判断该商品是否已经存在购物车内
        if (cart != null) {
            //如果该商品存在购物车中则将数量+1
            cart.setcNum(cart.getcNum() + 1);
            //调用更新购物车方法
            cartDao.updateCart(cart);
            //如果该商品不存在购物车中则添加
        }else{
            //调用根据商品Id查询的方法
            Product product = productDao.selectProductByPId(pId);
            //创建购物车实例化对象
            cart = new Cart();
            //添加数量
            cart.setcNum(1);
            //添加用户Id
            cart.setuId(uId);
            //添加商品信息
            cart.setProduct(product);
            //添加商品Id
            cart.setpId(Integer.parseInt(pId));
            //调用添加方法
            cartDao.insertCart(cart);
        }
    }

    /**
     * 查询购物车中商品的逻辑
     * @param uId
     * @return
     * @throws IllegalAccessException
     * @throws SQLException
     * @throws InvocationTargetException
     */
    @Override
    public List<Cart> findAll(Integer uId) throws IllegalAccessException, SQLException, InvocationTargetException {

        //调用根据用户Id查询购物车中商品的方法
        List<Cart> list = cartDao.selectCartByUid(uId);
        //返回查询到的结果
        return list;
    }

    /**
     * 删除购物车逻辑
     * @param cId
     * @throws SQLException
     */
    @Override
    public void deleteCartByCid(String cId) throws SQLException {

        //调用根据购物车Id删除的方法
        cartDao.deleteCartByCId(cId);

    }

    /**
     * 修改购物车逻辑
     * @param cId
     * @param cNum
     * @param price
     * @throws SQLException
     */
    @Override
    public void updateCart(String cId, String cNum, String price) throws SQLException {

        //调用更新购物车的方法
        cartDao.updateNumANDPrice(cId,cNum,price);

    }

    /**
     * 清空购物车逻辑
     * @param uId
     * @throws SQLException
     */
    @Override
    public void clearCart(String uId) throws SQLException {

        //调用根据用户Id删除的方法
        cartDao.deleteCartByUId(uId);

    }
}
